//
//  ViewController.m
//  点餐系统
//
//  Created by 伍银荣 on 2021/6/16.
//  Copyright © 2021 com.example. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()<UIPickerViewDelegate,UIPickerViewDataSource>
@property (nonatomic, strong) NSArray *foodsArr;
@property (strong, nonatomic) IBOutlet UILabel *fruitLbl;
@property (strong, nonatomic) IBOutlet UILabel *mainFoodLbl;
@property (strong, nonatomic) IBOutlet UILabel *drinkLbl;
- (IBAction)orderBtnClicked:(id)sender;
@property (strong, nonatomic) IBOutlet UIPickerView *pickView;

@end

@implementation ViewController

-(NSArray *)foodsArr {
    if (!_foodsArr) {
        _foodsArr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"foods.plist" ofType:nil]];
    }
    return _foodsArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    for (int i = 0; i < self.foodsArr.count; i++) {
        //[self.pickView selectRow:0 inComponent:i animated:YES];
        [self pickerView:self.pickView didSelectRow:0 inComponent:i];
    }
}

#pragma mark - 数据源方法
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return self.foodsArr.count;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return [self.foodsArr[component] count];
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    return self.foodsArr[component][row];
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSString *food = self.foodsArr[component][row];
    switch (component) {
        case 0:
            self.fruitLbl.text = food;
            break;
        case 1:
            self.mainFoodLbl.text = food;
            break;
        case 2:
            self.drinkLbl.text = food;
            break;
    }
    
}


- (IBAction)orderBtnClicked:(id)sender {
    for (int i = 0; i < self.foodsArr.count; i++) {
        //第i组中的所有数据
        NSUInteger count = [self.foodsArr[i] count];
        //生成随机数去选中
        uint32_t ranNum = arc4random_uniform((int)count);
        //获取第i组当前选中的行
        NSUInteger selRow = [self.pickView selectedRowInComponent:i];
        //判断随机数是否和当前选中的行一致
        while (selRow == ranNum) {
            ranNum = arc4random_uniform((int)count);
        }
        //实现滚动,让pickView选中数据
        [self.pickView selectRow:ranNum inComponent:i animated:YES];
        [self pickerView:self.pickView didSelectRow:ranNum inComponent:i];
    }
}

@end
